#include <rtthread.h>
#include <rtdevice.h>
#include "littlevgl2rtt.h"
#include "lvgl.h"
#include "gui_app_fwk.h"
#include "app_clock_main.h"
#include "app_mem.h"
#include "lv_ext_resource_manager.h"

// 定义秒表最大圈数
#define STOPWATCH_MAX_LAPS 100

// 秒表状态枚举
typedef enum {
    STOPWATCH_STATE_STOPPED,  // 停止状态
    STOPWATCH_STATE_RUNNING,  // 运行状态
} stopwatch_state_t;

// 秒表应用结构体
typedef struct {
    lv_obj_t *bg;              // 背景对象
    lv_obj_t *time_label;      // 时间显示标签
    lv_obj_t *start_stop_btn;  // 开始/停止按钮
    lv_obj_t *reset_lap_btn;   // 重置/计次按钮
    lv_obj_t *lap_list;        // 计次列表
    
    stopwatch_state_t state;   // 当前状态
    rt_tick_t start_tick;      // 开始计时的系统节拍数
    rt_tick_t elapsed_ticks;   // 已经过的节拍数
    rt_tick_t lap_ticks[STOPWATCH_MAX_LAPS];  // 各圈计时数组
    uint8_t lap_count;         // 当前圈数
    
    lv_timer_t *update_timer;  // 更新定时器
} app_clock_stopwatch_t;

// 秒表应用实例指针
static app_clock_stopwatch_t *p_clk_stopwatch = NULL;

// 更新秒表显示
static void update_stopwatch_display(void)
{
    rt_tick_t total_ticks;
    int hours, minutes, seconds, centiseconds;
    
    // 根据当前状态计算总节拍数
    if (p_clk_stopwatch->state == STOPWATCH_STATE_RUNNING) {
        total_ticks = p_clk_stopwatch->elapsed_ticks + (rt_tick_get() - p_clk_stopwatch->start_tick);
    } else {
        total_ticks = p_clk_stopwatch->elapsed_ticks;
    }
    
    // 将节拍数转换为小时、分钟、秒和百分之一秒
    int total_ms = (total_ticks * 1000) / RT_TICK_PER_SECOND;
    hours = total_ms / 3600000;
    minutes = (total_ms % 3600000) / 60000;
    seconds = (total_ms % 60000) / 1000;
    centiseconds = (total_ms % 1000) / 10;
    
    // 格式化时间字符串并更新显示
    char time_str[20];
    if (hours > 0) {
        rt_snprintf(time_str, sizeof(time_str), "%d h %02d min %02d s", 
                    hours, minutes, seconds);
    } else {
        rt_snprintf(time_str, sizeof(time_str), "%02d:%02d.%02d", 
                    minutes, seconds, centiseconds);
    }
    lv_label_set_text(p_clk_stopwatch->time_label, time_str);
    lv_obj_align_to(p_clk_stopwatch->time_label, p_clk_stopwatch->bg, LV_ALIGN_CENTER, 0, -20);
}

// 秒表更新定时器回调函数
static void stopwatch_update_timer_cb(lv_timer_t *timer)
{
    update_stopwatch_display();
}

// 开始秒表计时
static void start_stopwatch(void)
{
    if (p_clk_stopwatch->state == STOPWATCH_STATE_STOPPED) {
        p_clk_stopwatch->start_tick = rt_tick_get();  // 记录开始节拍数
        p_clk_stopwatch->state = STOPWATCH_STATE_RUNNING;  // 设置为运行状态
        // 更新按钮文本
        lv_obj_t *start_label = lv_obj_get_child(p_clk_stopwatch->start_stop_btn, 0);
        lv_label_set_text(start_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_stop)));
        lv_obj_t *reset_label = lv_obj_get_child(p_clk_stopwatch->reset_lap_btn, 0);
        lv_label_set_text(reset_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_lap)));
    }
}

// 停止秒表计时
static void stop_stopwatch(void)
{
    if (p_clk_stopwatch->state == STOPWATCH_STATE_RUNNING) {
        // 累计已过的节拍数
        p_clk_stopwatch->elapsed_ticks += rt_tick_get() - p_clk_stopwatch->start_tick;
        p_clk_stopwatch->state = STOPWATCH_STATE_STOPPED;  // 设置为停止状态
        // 更新按钮文本
        lv_obj_t *start_label = lv_obj_get_child(p_clk_stopwatch->start_stop_btn, 0);
        lv_label_set_text(start_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_start)));
        lv_obj_t *reset_label = lv_obj_get_child(p_clk_stopwatch->reset_lap_btn, 0);
        lv_label_set_text(reset_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_reset)));
    }
}

// 重置秒表
static void reset_stopwatch(void)
{
    p_clk_stopwatch->elapsed_ticks = 0;  // 清零累计节拍数
    p_clk_stopwatch->lap_count = 0;      // 清零圈数
    lv_obj_clean(p_clk_stopwatch->lap_list);  // 清空计次列表
    update_stopwatch_display();          // 更新显示
}

// 记录单圈时间
static void record_lap_time(void)
{
    if (p_clk_stopwatch->state == STOPWATCH_STATE_RUNNING && p_clk_stopwatch->lap_count < STOPWATCH_MAX_LAPS) {
        rt_tick_t current_ticks;
        // 计算当前总节拍数
        if (p_clk_stopwatch->state == STOPWATCH_STATE_RUNNING) {
            current_ticks = p_clk_stopwatch->elapsed_ticks + (rt_tick_get() - p_clk_stopwatch->start_tick);
        } else {
            current_ticks = p_clk_stopwatch->elapsed_ticks;
        }
        
        // 保存当前圈的节拍数
        p_clk_stopwatch->lap_ticks[p_clk_stopwatch->lap_count] = current_ticks;
        p_clk_stopwatch->lap_count++;
        
        // 使用当前总时间而不是单圈时间
        rt_tick_t total_time = current_ticks;
        
        // 将节拍数转换为时间单位
        int total_ms = (total_time * 1000) / RT_TICK_PER_SECOND;
        int hours = total_ms / 3600000;
        int minutes = (total_ms % 3600000) / 60000;
        int seconds = (total_ms % 60000) / 1000;
        int centiseconds = (total_ms % 1000) / 10;
        
        // 格式化单圈时间字符串
        char lap_str[48];
        if (hours > 0) {
            rt_snprintf(lap_str, sizeof(lap_str), "Lap %d: %d h %02d min %02d s", 
                        p_clk_stopwatch->lap_count, hours, minutes, seconds);
        } else {
            rt_snprintf(lap_str, sizeof(lap_str), "Lap %d: %02d:%02d.%02d", 
                        p_clk_stopwatch->lap_count, minutes, seconds, centiseconds);
        }
        
        // 创建并设置单圈时间标签
        lv_obj_t *lap_label = lv_label_create(p_clk_stopwatch->lap_list);
        lv_label_set_text(lap_label, lap_str);
        lv_obj_set_style_text_color(lap_label, lv_color_white(), 0);
        // 使用lv_ext_set_local_font设置正常字体，确保清晰显示且支持中文
        lv_ext_set_local_font(lap_label, FONT_NORMAL, LV_COLOR_WHITE);
    }
}

// 按钮事件回调函数
static void btn_event_cb(lv_event_t *e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *btn = lv_event_get_target(e);
    
    if (code == LV_EVENT_CLICKED) {
        // 判断点击的是哪个按钮并执行相应操作
        if (btn == p_clk_stopwatch->start_stop_btn) {
            if (p_clk_stopwatch->state == STOPWATCH_STATE_STOPPED) {
                start_stopwatch();
            } else {
                stop_stopwatch();
            }
        } else if (btn == p_clk_stopwatch->reset_lap_btn) {
            if (p_clk_stopwatch->state == STOPWATCH_STATE_STOPPED) {
                reset_stopwatch();
            } else {
                record_lap_time();
            }
        }
    }
}

// 恢复回调函数
static rt_int32_t resume_callback(void)
{
    // 如果定时器为空，则创建一个新的定时器
    if (p_clk_stopwatch && p_clk_stopwatch->update_timer == NULL) {
        p_clk_stopwatch->update_timer = lv_timer_create(stopwatch_update_timer_cb, 10, NULL);
    }
    return RT_EOK;
}

// 暂停回调函数
static rt_int32_t pause_callback(void)
{
    // 如果定时器存在，则删除定时器
    if (p_clk_stopwatch && p_clk_stopwatch->update_timer) {
        lv_timer_del(p_clk_stopwatch->update_timer);
        p_clk_stopwatch->update_timer = NULL;
    }
    return RT_EOK;
}

// 初始化函数
static rt_int32_t init(lv_obj_t *parent)
{
    // 分配内存并初始化结构体
    p_clk_stopwatch = (app_clock_stopwatch_t *)rt_malloc(sizeof(app_clock_stopwatch_t));
    RT_ASSERT(p_clk_stopwatch != NULL);
    rt_memset(p_clk_stopwatch, 0, sizeof(app_clock_stopwatch_t));
    
    // 创建背景对象
    p_clk_stopwatch->bg = lv_obj_create(parent);
    lv_obj_set_size(p_clk_stopwatch->bg, lv_obj_get_width(parent), lv_obj_get_height(parent));
    lv_obj_clear_flag(p_clk_stopwatch->bg, LV_OBJ_FLAG_SCROLLABLE);
    
    // 创建时间显示标签
    p_clk_stopwatch->time_label = lv_label_create(p_clk_stopwatch->bg);
    lv_label_set_text(p_clk_stopwatch->time_label, "00:00.00");
    // 使用lv_ext_set_local_font设置大号字体，确保清晰显示且支持中文
    lv_ext_set_local_font(p_clk_stopwatch->time_label, FONT_BIGL, LV_COLOR_WHITE);
    lv_obj_align(p_clk_stopwatch->time_label, LV_ALIGN_CENTER, 0, -30);
    
    // 创建按钮容器
    lv_obj_t *btn_container = lv_obj_create(p_clk_stopwatch->bg);
    lv_obj_set_size(btn_container, LV_HOR_RES_MAX, 90);
    lv_obj_align(btn_container, LV_ALIGN_BOTTOM_MID, 0, -20);
    lv_obj_set_flex_flow(btn_container, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(btn_container, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_clear_flag(btn_container, LV_OBJ_FLAG_SCROLLABLE);
    
    // 创建开始/停止按钮
    p_clk_stopwatch->start_stop_btn = lv_btn_create(btn_container);
    lv_obj_set_size(p_clk_stopwatch->start_stop_btn, 140, 80);
    lv_obj_add_event_cb(p_clk_stopwatch->start_stop_btn, btn_event_cb, LV_EVENT_CLICKED, NULL);
    
    // 设置开始/停止按钮标签
    lv_obj_t *start_stop_label = lv_label_create(p_clk_stopwatch->start_stop_btn);
    lv_label_set_text(start_stop_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_start)));
    // 使用lv_ext_set_local_font设置正常字体，确保清晰显示且支持中文
    lv_ext_set_local_font(start_stop_label, FONT_BIGL, LV_COLOR_WHITE);
    lv_obj_center(start_stop_label);
    
    // 创建重置/计次按钮
    p_clk_stopwatch->reset_lap_btn = lv_btn_create(btn_container);
    lv_obj_set_size(p_clk_stopwatch->reset_lap_btn, 140, 80);
    lv_obj_add_event_cb(p_clk_stopwatch->reset_lap_btn, btn_event_cb, LV_EVENT_CLICKED, NULL);
    
    // 设置重置/计次按钮标签
    lv_obj_t *reset_lap_label = lv_label_create(p_clk_stopwatch->reset_lap_btn);
    lv_label_set_text(reset_lap_label, LV_EXT_STR_GET(LV_EXT_STR_ID(stopwatch_reset)));
    // 使用lv_ext_set_local_font设置正常字体，确保清晰显示且支持中文
    lv_ext_set_local_font(reset_lap_label, FONT_BIGL, LV_COLOR_WHITE);
    lv_obj_center(reset_lap_label);
    
    // 创建计次列表
    p_clk_stopwatch->lap_list = lv_obj_create(p_clk_stopwatch->bg);
    lv_obj_set_size(p_clk_stopwatch->lap_list, LV_HOR_RES_MAX - 20, 100);
    lv_obj_align_to(p_clk_stopwatch->lap_list, p_clk_stopwatch->time_label, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
    lv_obj_set_flex_flow(p_clk_stopwatch->lap_list, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_style_pad_all(p_clk_stopwatch->lap_list, 5, 0);
    lv_obj_set_style_pad_row(p_clk_stopwatch->lap_list, 3, 0);
    // 保留滚动功能，移除清除滚动标志的代码
    // lv_obj_clear_flag(p_clk_stopwatch->lap_list, LV_OBJ_FLAG_SCROLLABLE);
    
    // 创建定时器用于更新秒表显示
    p_clk_stopwatch->update_timer = lv_timer_create(stopwatch_update_timer_cb, 10, NULL);
    
    return RT_EOK;
}

// 反初始化函数
static rt_int32_t deinit(void)
{
    // 释放内存
    if (p_clk_stopwatch) {
        if (p_clk_stopwatch->update_timer) {
            lv_timer_del(p_clk_stopwatch->update_timer);
        }
        rt_free(p_clk_stopwatch);
        p_clk_stopwatch = NULL;
    }
    return RT_EOK;
}

// 秒表操作函数集合
static const app_clock_ops_t ops = {
    .init = init,
    .pause = pause_callback,
    .resume = resume_callback,
    .deinit = deinit,
};

// 注册秒表应用
void app_clock_stopwatch_register(void)
{
    app_clock_register("stopwatch", &ops);
}